const Service = require('egg').Service;

class SequelizeService extends Service {
    /**
     * 分页
     * @param {数据库Model名称} modelName 
     * @param {分页及查询数据} param1 
     */
    async pages(modelName, { limit = 20, offset = 1 ,...where}) {
        const db = this.ctx.model[modelName];
        const data = await db.findAndCountAll({
            limit: limit,
            where,
            offset: (offset - 1) * limit
        })
        return {
            ...data, limit, offset
        }
    }

    /**
     * list
     * @param {数据库Model名称} modelName 
     * @param {查询数据} where 
     */
    async list(modelName, where) {
        const db = this.ctx.model[modelName];
        const data = await db.findAll({
            where,
        })
        return {
            data
        }
    }

    /**
     * 插入
     * @param {*} modelName 
     * @param {*} params 
     */
    async insert(modelName, params) {
        const db = this.ctx.model[modelName];
        const data = await db.create(params)
        return data&&data
    }
    /**
     * 删除
     * @param {*} modelName 
     * @param {*} params 
     */
    async delete(modelName, params) {
        const db = this.ctx.model[modelName];
        const data = await db.destroy({
            where:{
                ...params
            }
        })
        return data>0
    }
    /**
     * 更新
     * @param {*} modelName 
     * @param {*} params 
     * @param {筛选项目} filterItem 默认为id
     */
    async update(modelName, params,filterItems=['id']) {
        console.log(params)
        const db = this.ctx.model[modelName];
        const where={}
        filterItems.forEach(item=>{
           where[item] = params[item]     
        })
        const data = await db.update(params,{
            where:where
        })
        return data>0
    }
}

module.exports = SequelizeService;